<template>
    <div class="table-form-page">
        <div class="form-page-header">
            <div>
                <el-page-header @back="closeWindow" content="项目投标" />
            </div>
            <div>
                <el-button v-show="showSaveBtn" type="primary" @click="onSubmit">保存</el-button>
                <el-popconfirm
                    v-if="showSubmitBtn"
                    title="确认提交审核吗？"
                    confirmButtonText="确定"
                    cancelButtonText="再考虑一下"
                    @confirm="onFlowSub"
                >
                    <template #reference>
                        <el-button type="primary">提交</el-button>
                    </template>
                </el-popconfirm>
                <!-- <el-button v-show="showSubmitBtn" type="primary" @click="onFlowSub">提交</el-button> -->
                <el-button v-show="showReviewBtn" type="primary" @click="onReview">审核</el-button>
                <el-button v-show="showResultSaveBtn" type="primary" @click="submitResult">保存中标结果</el-button>

                <el-popconfirm
                    v-if="showResultConfirmBtn"
                    title="确认中标结果后将不可修改，并且更新项目信息，确定继续？"
                    confirmButtonText="确定"
                    cancelButtonText="再考虑一下"
                    @confirm="confirmResult"
                >
                    <template #reference>
                        <el-button type="primary">确认中标结果</el-button>
                    </template>
                </el-popconfirm>
                <!-- <el-button type="default" @click="onPrint">打印</el-button> -->
            </div>
        </div>
        <div class="form-content">
            <table class="table-class" border="0" cellspacing="0" cellpadding="0">
                <col class="label-col" />
                <col class="content-col" />
                <col class="label-col" />
                <col class="content-col" />
                <tr class="tr-class">
                    <td class="tab-class" colspan="4">项目投标信息</td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">项目名称</td>
                    <td class="td-class content-class" colspan="3">
                        <el-input
                            v-model="form.projectName"
                            class="form-input-class"
                            placeholder="请选择"
                            readonly
                            @click="chooseProject"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">项目编码</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.projectCode" class="form-input-class" placeholder="请选择" />
                    </td>
                    <td class="td-class label-class">业务类型</td>
                    <td class="td-class content-class">
                        <el-select v-model="form.businessType" placeholder="请选择" style="width: 100%">
                            <el-option
                                v-for="item in businessTypeOption"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">项目所在地</td>
                    <td class="td-class content-class">
                        <el-cascader
                            ref="areaRef"
                            v-model="form.projectAddrCode"
                            :options="area"
                            style="width: 100%"
                            placeholder="请选择"
                        />
                    </td>
                    <td class="td-class label-class">承担部门</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.departmentName"
                            class="form-input-class"
                            placeholder="请选择"
                            readonly
                            @click="chooseDepartment"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">办事处</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.branchOffice"
                            class="form-input-class"
                            placeholder="点击选择"
                            readonly
                            @click="chooseOffice"
                        />
                    </td>
                    <td class="td-class label-class">区域事业部</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.division"
                            class="form-input-class"
                            placeholder="请选择办事处"
                            readonly
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">限价（元）</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.priceLimit" class="form-input-class" placeholder="请输入限价" />
                    </td>
                    <td class="td-class label-class">业主单位</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.owners" class="form-input-class" placeholder="请输入业主单位" />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">投标保证金（元）</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.amountOfDeposit"
                            class="form-input-class"
                            placeholder="请输入投标保证金金额"
                        />
                    </td>
                    <td class="td-class label-class">保证金缴纳时间</td>
                    <td class="td-class content-class">
                        <el-date-picker
                            v-model="form.depositPayDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                            class="form-input-class"
                            placeholder="选择日期"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">联系人</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.contact" class="form-input-class" placeholder="请输入联系人" />
                    </td>
                    <td class="td-class label-class">联系方式</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.phone" class="form-input-class" placeholder="请输入联系方式" />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">开标负责人</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.bidCharge" class="form-input-class" placeholder="请输入开标负责人" />
                    </td>
                    <td class="td-class label-class">开标日期</td>
                    <td class="td-class content-class">
                        <el-date-picker
                            v-model="form.bidDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                            class="form-input-class"
                            placeholder="选择日期"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">开标地点</td>
                    <td class="td-class content-class" colspan="3">
                        <el-input v-model="form.bidAddr" class="form-input-class" placeholder="请输入开标地点" />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">技术标计划完成时间</td>
                    <td class="td-class content-class">
                        <el-date-picker
                            v-model="form.techPlanDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                            class="form-input-class"
                            placeholder="选择日期"
                        />
                    </td>
                    <td class="td-class label-class">商务标计划完成时间</td>
                    <td class="td-class content-class">
                        <el-date-picker
                            v-model="form.busPlanDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                            class="form-input-class"
                            placeholder="选择日期"
                        />
                    </td>
                </tr>
                <tbody v-if="form.state === 99">
                    <tr class="tr-class">
                        <td class="tab-class" colspan="4">中标结果信息</td>
                    </tr>
                    <tr class="tr-class">
                        <td class="td-class label-class">中标结果</td>
                        <td class="td-class content-class">
                            <el-select v-model="form.bidState" placeholder="请选择" style="width: 100%">
                                <el-option key="1" label="中标" :value="1"></el-option>
                                <el-option key="2" label="未中标" :value="2"></el-option>
                                <el-option key="3" label="流标" :value="3"></el-option>
                            </el-select>
                        </td>
                        <td class="td-class label-class">报价（元）</td>
                        <td class="td-class content-class">
                            <el-input v-model="form.quote" placeholder="请输入报价" class="form-input-class" />
                        </td>
                    </tr>
                    <tr class="tr-class">
                        <td class="td-class label-class">中标单位名称</td>
                        <td class="td-class content-class" colspan="3">
                            <el-input
                                v-model="form.bidderName"
                                class="form-input-class"
                                placeholder="请输入中标单位名称"
                            />
                        </td>
                    </tr>
                    <tr class="tr-class">
                        <td class="td-class label-class">中标单位排名</td>
                        <td class="td-class content-class">
                            <el-input
                                v-model="form.bidderRank"
                                class="form-input-class"
                                placeholder="请输入中标单位排名"
                            />
                        </td>
                        <td class="td-class label-class">中标单位报价（元）</td>
                        <td class="td-class content-class">
                            <el-input
                                v-model="form.bidderQuote"
                                class="form-input-class"
                                placeholder="请输入中标单位报价"
                            />
                        </td>
                    </tr>
                    <tr class="tr-class" v-if="form.bidState === 1">
                        <td class="td-class label-class">中标金额（元）</td>
                        <td class="td-class content-class">
                            <el-input v-model="form.bidPrice" class="form-input-class" placeholder="请输入中标金额" />
                        </td>
                        <td class="td-class label-class">暂定金（元）</td>
                        <td class="td-class content-class">
                            <el-input v-model="form.tempDeposit" class="form-input-class" placeholder="请输入暂定金" />
                        </td>
                    </tr>
                    <tr class="tr-class" v-if="form.bidState === 1">
                        <td class="td-class label-class">经营性分包金额（元）</td>
                        <td class="td-class content-class">
                            <el-input
                                v-model="form.subcontractFee"
                                class="form-input-class"
                                placeholder="请输入经营性分包金额"
                            />
                        </td>
                        <td class="td-class label-class">经营费比例(%)</td>
                        <td class="td-class content-class">
                            <el-input
                                v-model="form.operationFeeRatio"
                                class="form-input-class"
                                placeholder="请输入经营费比例"
                            />
                        </td>
                    </tr>
                    <tr class="tr-class" v-if="form.bidState === 2 || form.bidState === 3">
                        <td class="td-class label-class">未中标原因</td>
                        <td class="td-class content-class" colspan="">
                            <el-input
                                v-model="form.bidOutReason"
                                type="textarea"
                                class="form-input-class"
                                :rows="5"
                                placeholder="请输入未中标原因"
                            />
                        </td>
                    </tr>
                </tbody>

                <tr class="tr-class">
                    <td class="tab-class" colspan="4">附件</td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class" colspan="4">
                        <div v-if="showUploadBtn" style="padding: 10px">
                            <el-upload
                                class="upload-demo"
                                :action="uploadUrl"
                                :headers="uploadHeaders"
                                :data="uploadParams"
                                :on-success="onFileUploadSuccess"
                                :show-file-list="false"
                            >
                                <el-button type="primary">点击上传</el-button>
                            </el-upload>
                        </div>
                        <el-table :data="attachments" border>
                            <el-table-column type="index" width="80" label="序号" />
                            <el-table-column prop="fileName" label="文件名" />
                            <el-table-column label="文件类型" width="200">
                                <template #default="scope">
                                    <span v-if="scope.row.category === 1">技术标文件</span>
                                    <span v-else-if="scope.row.category === 2">商务标文件</span>
                                    <span v-else>投标文件</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="createTime" label="上传时间" width="200" />
                            <el-table-column fixed="right" label="操作" width="160">
                                <template #default="scope">
                                    <el-button type="primary" @click="handlePreview(scope.row)" size="small">
                                        预览
                                    </el-button>
                                    <el-popconfirm
                                        v-if="showUploadBtn"
                                        title="移除后数据将不可恢复，确认移除吗？"
                                        confirmButtonText="确定"
                                        cancelButtonText="再考虑一下"
                                        @confirm="handleRemove(scope.row)"
                                    >
                                        <template #reference>
                                            <el-button type="danger" size="small">移除</el-button>
                                        </template>
                                    </el-popconfirm>
                                </template>
                            </el-table-column>
                        </el-table>
                    </td>
                </tr>
                <tr class="tr-class" v-if="showTechProcess">
                    <td class="tab-class" colspan="4">技术标审核流程</td>
                </tr>
                <tr class="tr-class" v-if="showTechProcess">
                    <td class="td-class" colspan="4">
                        <FlowCpt
                            ref="techProcessRef"
                            flowType="BID_TECH"
                            :disabled="!showSaveBtn"
                            :taskId="form.techId"
                        ></FlowCpt>
                    </td>
                </tr>
                <tr class="tr-class" v-if="showTechFlowHis">
                    <td class="tab-class" colspan="4">技术标审批记录</td>
                </tr>
                <tr class="tr-class" v-if="showTechFlowHis">
                    <td class="td-class" colspan="4">
                        <FlowHistoryCpt :taskId="form.techId" />
                    </td>
                </tr>
                <tr class="tr-class" v-if="showBusProcess">
                    <td class="tab-class" colspan="4">商务标审核流程</td>
                </tr>
                <tr class="tr-class" v-if="showBusProcess">
                    <td class="td-class" colspan="4">
                        <FlowCpt
                            ref="busProcessRef"
                            flowType="BID_BUS"
                            :disabled="!showSaveBtn"
                            :taskId="form.busId"
                        ></FlowCpt>
                    </td>
                </tr>
                <tr class="tr-class" v-if="showBusFlowHis">
                    <td class="tab-class" colspan="4">商务标审批记录</td>
                </tr>
                <tr class="tr-class" v-if="showBusFlowHis">
                    <td class="td-class" colspan="4">
                        <FlowHistoryCpt :taskId="form.busId" />
                    </td>
                </tr>
            </table>
        </div>

        <FlowOperationCpt v-if="showReviewDialog" :data="reviewForm" @close="closeReviewDialog"></FlowOperationCpt>

        <!-- 项目弹框 -->
        <el-dialog
            title="项目信息"
            v-model="showProjectGridCpt"
            width="80%"
            :lock-scroll="true"
            :close-on-click-modal="false"
            destroy-on-close
        >
            <ProjectGridCpt
                v-if="showProjectGridCpt"
                statuses="'TEMP', 'IN_BID'"
                @select="projectSelected"
            ></ProjectGridCpt>
        </el-dialog>

        <el-dialog
            width="400px"
            top="20vh"
            title="部门"
            v-model="showDepartment"
            :lock-scroll="true"
            :close-on-click-modal="false"
        >
            <div class="tree-dialog-content">
                <department-tree @select="departmentSelected"></department-tree>
            </div>
        </el-dialog>

        <el-dialog
            width="800px"
            top="10vh"
            title="办事处"
            v-model="showOfficeGridCpt"
            :lock-scroll="true"
            :close-on-click-modal="false"
        >
            <div class="dialog-content">
                <OfficeGridCpt :single="true" @select="officeSelected"></OfficeGridCpt>
            </div>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElNotification } from 'element-plus'
import http from '@/http.js'
import { store } from '@/store'
import area from '@/api/area.json'
import DepartmentTree from '@/components/bas/DepartmentTree.vue'
import ProjectGridCpt from '@/components/pub/ProjectGridCpt.vue'
import OfficeGridCpt from '@/components/pub/OfficeGridCpt.vue'
import FlowCpt from '@/components/process/FlowCpt.vue'
import FlowOperationCpt from '@/components/process/FlowOperationCpt.vue'
import FlowHistoryCpt from '@/components/process/FlowHistoryCpt.vue'

const props = defineProps({
    id: {
        type: String,
        default: ''
    },
    bidsType: {
        type: String,
        default: 'BID_MAIN'
    }
})

const emit = defineEmits(['close'])

onMounted(() => {
    loadOptions()
    if (props.id !== '') {
        loadDetail()
    } else {
        showSaveBtn.value = true
        showUploadBtn.value = true
        showTechProcess.value = true
        showBusProcess.value = true
    }
})

const areaRef = ref(null)
const showSaveBtn = ref(false)

const showDepartment = ref(false)
const showTechFlowHis = ref(false)
const showBusFlowHis = ref(false)
const showPrint = ref(false)

const showTechProcess = ref(false)
const showBusProcess = ref(false)

const techProcessRef = ref(null)
const busProcessRef = ref(null)

const showSubmitBtn = ref(false)
const showUploadBtn = ref(false)
const showResultSaveBtn = ref(false)
const showResultConfirmBtn = ref(false)
const showReviewBtn = ref(false)
const showReviewDialog = ref(false)

// 表单的ID一直是主单据ID，流程根据类型使用techId和busId
const form = reactive({
    id: '',
    projectId: '',
    projectCode: '',
    projectName: '',
    businessType: '',
    projectAddrCode: '',
    projectAddrName: '',
    departmentId: '',
    departmentCode: '',
    departmentName: '',
    branchOffice: '',
    customerManager: '',
    division: '',
    marketingDirector: '',
    priceLimit: '',
    amountOfDeposit: '',
    depositPayDate: '',
    owners: '',
    contact: '',
    phone: '',
    bidCharge: '',
    bidDate: '',
    bidAddr: '',
    flowTypeCode: 'BID_MAIN',
    state: '',
    techId: '',
    techPlanDate: '',
    busId: '',
    busPlanDate: '',
    flowList: [],
    techFlowList: [],
    busFlowList: [],
    lander: ''
})

const attachments = ref([])

const businessTypeOption = ref([])

const loadOptions = () => {
    http.fetchForm({
        url: '/sys/dictionary/queryByGroups',
        method: 'get',
        data: {
            groupCodes: 'P-004-001'
        }
    }).then((res) => {
        businessTypeOption.value = res.data['P-004-001']
    })
}

const loadDetail = () => {
    http.fetchForm({
        url: '/jingying/bids/find',
        method: 'get',
        data: {
            id: props.id,
            type: props.bidsType
        }
    }).then((res) => {
        let data = res.data
        data['projectAddrCode'] = data.projectAddrCode.split(',')
        Object.assign(form, data)
        if (props.bidsType === 'BID_TECH' || props.bidsType === 'BID_MAIN') {
            showTechProcess.value = true
            showTechFlowHis.value = true
        }
        if (props.bidsType === 'BID_BUS' || props.bidsType === 'BID_MAIN') {
            showBusProcess.value = true
            showBusFlowHis.value = true
        }

        // 显示保存按钮条件
        let currentUser = localStorage.getItem('username')
        if (data.state === 0 && data.createBy === currentUser) {
            showSaveBtn.value = true
            showUploadBtn.value = true
        } else {
            showSaveBtn.value = false
        }

        // 不同类型的按钮控制
        if (props.bidsType === 'BID_MAIN') {
            // showUploadBtn.value = false
            showSubmitBtn.value = false
        } else if (props.bidsType === 'BID_RESULT') {
            showUploadBtn.value = true
        } else if (props.bidsType === 'BID_TECH' || props.bidsType === 'BID_BUS') {
            if (data.handler === currentUser && data.state === 1) {
                showUploadBtn.value = true
                showSubmitBtn.value = true
            } else {
                showUploadBtn.value = false
                showSubmitBtn.value = false
            }
        }

        if (form.state === 99) {
            let roles = localStorage.getItem('roles')
            if (roles.indexOf('ROLE_JYZY') > -1 && !data.bidStateConfirmed) {
                showResultSaveBtn.value = true
            }
            if (roles.indexOf('ROLE_FGFZR') > -1 && !data.bidStateConfirmed) {
                showResultConfirmBtn.value = true
            }
        }

        // 显示审批按钮条件
        if (data.state !== 0 && data.state !== 1 && data.handler === currentUser) {
            showReviewBtn.value = true
        } else {
            showReviewBtn.value = false
        }

        // 将上传的文件源ID设为主单据ID，方便主单据查看所有附件
        uploadParams.sId = data.id
        loadAttachments()
    })
}

const loadAttachments = () => {
    http.fetchForm({
        url: '/jingying/bids/file_list',
        method: 'get',
        data: {
            sId: form.id,
            type: props.bidsType
        }
    }).then((res) => {
        attachments.value = res.data
    })
}

const onSubmit = () => {
    let params = JSON.parse(JSON.stringify(form))
    params['projectAddrCode'] = params.projectAddrCode.join(',')
    params['projectAddrName'] = areaRef.value.getCheckedNodes()[0].text
    let techProcessData = techProcessRef.value.processList
    let busProcessData = busProcessRef.value.processList
    params['techFlowList'] = techProcessData
    params['busFlowList'] = busProcessData
    params['lander'] = localStorage.getItem('username')
    // 如果是新增，附件放到参数中保存
    if (params.id === '') {
        params['attachments'] = attachments.value
    }
    http.fetchJson({
        url: '/jingying/bids/save',
        data: params
    }).then((res) => {
        ElNotification({
            title: '提示',
            message: '保存成功',
            type: 'success'
        })
        closeWindow()
    })
}

/**
 * 保存中标结果
 */
const submitResult = () => {
    let params = JSON.parse(JSON.stringify(form))
    http.fetchJson({
        url: '/jingying/bids/result_submit',
        data: params
    }).then((res) => {
        ElNotification({
            title: '提示',
            message: '保存成功',
            type: 'success'
        })
        closeWindow()
    })
}

/**
 * 确认中标结果
 */
const confirmResult = () => {
    let params = JSON.parse(JSON.stringify(form))
    http.fetchJson({
        url: '/jingying/bids/result_confirm',
        data: params
    }).then((res) => {
        ElNotification({
            title: '提示',
            message: '保存成功',
            type: 'success'
        })
        closeWindow()
    })
}

/**
 * 项目选择
 */
const showProjectGridCpt = ref(false)
const chooseProject = () => {
    showProjectGridCpt.value = true
}

const projectSelected = (res) => {
    let project = res[0]
    form.projectId = project.id
    form.projectCode = project.code
    form.projectName = project.name
    form.businessType = project.businessType
    form.departmentId = project.departmentId
    form.departmentCode = project.departmentCode
    form.departmentName = project.departmentName
    form.wayOfGet = project.wayOfGet
    if (project.addrCode !== null && project.addrCode !== '') {
        form.projectAddrCode = project.addrCode.split(',')
        form.projectAddrName = project.addrName
    }
    form.branchOffice = project.branchOffice
    form.division = project.division
    form.owners = project.clientCompanyName
    showProjectGridCpt.value = false
}

/**
 * 选择部门
 * 1:承担部门、2:主办部门、3:协办部门
 */
const chooseDepartment = (type) => {
    showDepartment.value = true
}

const departmentSelected = (res) => {
    form.departmentId = res.id
    form.departmentCode = res.code
    form.departmentName = res.label
    showDepartment.value = false
}

/**
 * 办事处选择
 */
const showOfficeGridCpt = ref(false)

const chooseOffice = () => {
    showOfficeGridCpt.value = true
}

const officeSelected = (res) => {
    form.branchOffice = res.name
    form.division = res.division
    showOfficeGridCpt.value = false
}

const closeWindow = () => {
    emit('close')
}

const uploadUrl = ref(import.meta.env.VITE_API_URL + '/jingying/bids/file_upload')
const uploadHeaders = reactive({
    Authorization: localStorage.getItem('token')
})

const uploadParams = reactive({
    sId: '',
    type: props.bidsType
})

const onFileUploadSuccess = (response) => {
    console.log(response)
    if (response.data) {
        attachments.value.push(response.data)
    } else {
        loadAttachments()
    }
}

const handlePreview = (row) => {
    let url = import.meta.env.VITE_API_URL + '/attachment/' + row.storageName
    window.open(url)
}

const handleRemove = (row) => {
    http.fetchForm({
        url: '/jingying/bids/file_delete',
        method: 'post',
        data: {
            id: row.id
        }
    }).then((res) => {
        ElNotification({
            title: '提示',
            message: '移除成功',
            type: 'success'
        })
        loadAttachments()
    })
}

const onFlowSub = () => {
    http.fetchJson({
        url: '/flow/task/submit',
        data: {
            flowTypeCode: props.bidsType,
            taskId: props.id,
            state: form.state,
            operation: 'submit'
        }
    }).then((res) => {
        ElNotification({
            title: '提示',
            message: '提交成功',
            type: 'success'
        })
        loadDetail()
    })
}

const reviewForm = reactive({
    id: props.id,
    state: 0,
    flowTypeCode: props.bidsType
})

const onReview = () => {
    reviewForm.state = form.state
    showReviewDialog.value = true
}

const closeReviewDialog = (refresh) => {
    showReviewDialog.value = false
    if (refresh) {
        loadDetail()
    }
}
</script>
<style scoped>
@import '@/assets/css/table-form.css';
</style>
